﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Modeling;
using System.Diagnostics;

namespace DSLFactory.VSCTDesigner
{
    [RuleOn(typeof(IDSymbol), FireTime = TimeToFire.TopLevelCommit)]
    class IDSymbolAddRule : AddRule
    {
        public override void ElementAdded(ElementAddedEventArgs e)
        {
            // Calcul de la valeur
            IDSymbol symbol = e.ModelElement as IDSymbol;
            if( symbol.Value != "?" )
                return;

            int max = 0x30000 - 1;

            // Recherche de la valeur la + grande
            symbol.GuidSymbol.IDSymbols.ForEach(item =>
            {
                if( item != symbol && item.Value != "?")
                {
                    string str = item.Value;
                    if( !String.IsNullOrEmpty(str) )
                    {
                        int v = 0;
                        if( str.StartsWith("0x") )
                        {
                            str = str.Substring(2);
                            v = Int32.Parse(str, System.Globalization.NumberStyles.HexNumber);
                        }
                        else if( str[0] != '{' && str != "Extern" )
                            v = Int32.Parse(str);

                        if( v > max )
                            max = v;
                    }
                }
            });

            symbol.Value = String.Format("0x{0:X}", ( max + 1 ));
        }
    }
}
